<script setup lang="tsx">
import type { FormSchema } from '@/components/Form'
import { ref, reactive, unref, watch } from 'vue'
import { ElDialog } from 'element-plus'
import { Search } from '@/components/Search'
import { Table, type TableColumn } from '@/components/Table'
import { BaseButton } from '@/components/Button'
import { useTable } from '@/hooks/web/useTable'
import { useSearch } from '@/hooks/web/useSearch'
import { getListStorageApi } from '@/api/warehouse'
import { searchWarehouseCateApi, searchWarehouseAreaCateApi } from '@/api/utils/search'
const { title, rowListData } = defineProps({
  title: String,
  rowListData: {
    type: String,
    required: true
  }
})
const show = defineModel({ type: Boolean, default: false })
watch(show, async (val) => {
  if (!val) {
    const elTableRef = await getElTableExpose()
    elTableRef?.clearSelection()
  }
})
const { searchRegister, searchMethods } = useSearch()
const { setSchema } = searchMethods
const searchUser = async (query) => {
  if (query && Object.values(query).every((item) => item !== '')) {
    setSchema([
      {
        field: 'warehouse_id',
        path: 'componentProps.loading',
        value: true
      }
    ])
    const params = {
      ...query,
      field: 'id,name'
    }
    const res = await searchWarehouseCateApi(params)
    if (res) {
      setSchema([
        {
          field: 'warehouse_id',
          path: 'componentProps.options',
          value: res.data.list.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      ])
    }
    setSchema([
      {
        field: 'warehouse_id',
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const searchUsered = async (query) => {
  if (query && Object.values(query).every((item) => item !== '')) {
    setSchema([
      {
        field: 'warehouse_area_id',
        path: 'componentProps.loading',
        value: true
      }
    ])
    const params = {
      ...query,
      field: 'id,name'
    }
    const res = await searchWarehouseAreaCateApi(params)
    if (res) {
      setSchema([
        {
          field: 'warehouse_area_id',
          path: 'componentProps.options',
          value: res.data.list.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      ])
    }
    setSchema([
      {
        field: 'warehouse_area_id',
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const emit = defineEmits(['change'])
const TableSchema = reactive<TableColumn[]>([
  {
    field: 'warehouse_name',
    label: '仓库名称'
  },
  {
    field: 'warehouse_area_name',
    label: '库区名称'
  },
  {
    field: 'name',
    label: '库位编码'
  },
  {
    field: 'purchasing_price',
    label: '库位状态',
    formatter: (row) => {
      return Number(row.quantity) > 0 ? '已有货物' : '暂无货物'
    }
  },
  {
    field: 'goods_type',
    label: '商品种数'
  },
  {
    field: 'quantity',
    label: '商品数量'
  },
  {
    field: 'action',
    label: '操作',
    slots: {
      default: ({ row }) => {
        return (
          <>
            <BaseButton type="primary" onClick={() => submit(row)}>
              选择此库位
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchParams = ref({})
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'warehouse_id',
    label: '仓库名称',
    component: 'Select',
    componentProps: {
      placeholder: '支持模糊搜索',
      filterable: true,
      remote: true,
      loading: false,
      remoteMethod: (name) => searchUser({ name }),
      options: [],
      on: {
        change: (val) => {
          searchParams.value.warehouse_id = val
        }
      }
    }
  },
  {
    field: 'warehouse_area_id',
    label: '库区名称',
    component: 'Select',
    componentProps: {
      placeholder: '支持模糊搜索',
      filterable: true,
      remote: true,
      loading: false,
      remoteMethod: (name) => searchUsered({ name }),
      options: [],
      on: {
        change: (val) => {
          searchParams.value.warehouse_area_id = val
        }
      }
    }
  },
  {
    field: 'name',
    label: '库区编码',
    component: 'Input'
  }
])
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListStorageApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      company_id: rowListData,
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose } = tableMethods

const submit = async (row) => {
  emit('change', unref(row))
  show.value = false
}
</script>

<template>
  <ElDialog v-model="show" :title="title">
    <div class="flex">
      <div class="flex-auto">
        <Search
          @register="searchRegister"
          :schema="searchSchema"
          @search="setSearchParams"
          @reset="setSearchParams"
        />
        <Table
          v-model:pageSize="pageSize"
          v-model:currentPage="currentPage"
          class="w-full"
          height="50vh"
          :columns="TableSchema"
          :data="dataList"
          :loading="loading"
          :pagination="{ total }"
          @register="tableRegister"
        />
      </div>
    </div>
  </ElDialog>
</template>
